<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;

class CheckParams
{
    public function handle(Request $request, \Closure $next)
    {
        $input = $request->input();
        $methodName = $request->route()->getAction()['controller'];
        $ref = new \ReflectionClass($request->route()->controller);
        $refMethod = $ref->getMethod(explode('@', $methodName)[1]);
        $doc = $refMethod->getDocComment();

        $apiName = '';
        $apiParams = [];
        $apiClass = explode('@', $methodName)[0];
        $apiFunction = explode('@', $methodName)[1];

        foreach (explode("\n", $doc) as $v) {
            if (stripos($v, '/**') !== FALSE || stripos($v, '*/') !== FALSE) continue;
            if (stripos($v, '@api') !== FALSE) {
                $apiName = trim(str_replace('* @api', '', $v));
            }
            if (stripos($v, '@param') !== FALSE) {
                $p = explode(' ', trim(str_replace('* @param', '', $v)));
                $apiParams[] = [
                    'type' => $p[0],
                    'key' => $p[1],
                    'required' => strtolower($p[2]) === 'required',
                    'desc' => $p[3]
                ];
            }
        }

        $rules = [
            'apiName' => $apiName,
            'apiParams' => $apiParams,
            'apiClass' => $apiClass,
            'apiFunction' => $apiFunction
        ];
        $request->paramRules = $rules;

        $params = [];
        $needButNone = [];
        foreach ($rules['apiParams'] as $v) {
            if (!isset($v['key'])) continue;
            $key = $v['key'];
            if ($v['required'] && !isset($input[$key])) {
                $needButNone[] = $v['desc'] ?? '';
            }

            $input[$key] = $input[$key] ?? '';

            switch ($v['type']) {
                case 'String': $value = (string)$input[$key]; break;
                case 'int': $value = (int)$input[$key]; break;
                case 'float': $value = (float)$input[$key]; break;
                default: $value = $input[$key];
            }
            $params[$key] = $value;
        }

        if (!empty($needButNone)) {
            die(json_encode([
                'code' => 10006,
                'msg' => '缺少必要参数：' . implode(',', $needButNone),
                'data' => []
            ]));
        }
        $request->params = $params;

        $next($request);
    }
}
